/*
Copyright 2010,2011 Matt Van Der Westhuizen

This file is part of CGLL.

CGLL is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

CGLL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with CGLL.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.chaoticengine.cgll.serialization;

import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import org.simpleframework.xml.convert.Converter;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;

/**
 * Simple XML converter for the Slick2D class Rectangle.
 *
 * @author Matt v.d. Westhuizen
 */
public class FontConvertor implements Converter<Font> {
    public Font read(InputNode in) throws Exception {
        String filename = "";
        int ptSize = 12;
        boolean bold = false;
        boolean italic = false;
        Color col = Color.white;

        InputNode n = in.getNext();
        while (n != null) {
            if (n.getName().equals("filename")) {
                filename = n.getValue();
            } else if (n.getName().equals("size")) {
                ptSize = Integer.parseInt(n.getValue());
            } else if (n.getName().equals("bold")) {
                bold = Boolean.parseBoolean(n.getValue());
            } else if (n.getName().equals("italic")) {
                italic = Boolean.parseBoolean(n.getValue());
            } else if (n.getName().equals("color")) {
                col = new ColorConverter().read(n);
            }
            
            n = in.getNext();
        }

        UnicodeFont fnt = new UnicodeFont(filename, ptSize, bold, italic);
        fnt.getEffects().add(new ColorEffect(new java.awt.Color(col.r, col.g, col.b, col.a)));
        fnt.addAsciiGlyphs();
        fnt.addGlyphs("-_()");
        fnt.loadGlyphs();

        return(fnt);
    }

    public void write(OutputNode on, Font f) throws Exception {
        UnicodeFont fnt = (UnicodeFont) f;
        on.getChild("filename").setValue(fnt.getFontFile());
        on.getChild("size").setValue("" + fnt.getLineHeight());
        on.commit();
    }
}
